package com.by.controller;

import cn.hutool.core.bean.BeanUtil;
import com.by.auth.TokenTemplate;
import com.by.common.controller.BaseController;
import com.by.common.entity.PageBean;
import com.by.common.entity.ResultBean;
import com.by.common.group.ISave;
import com.by.common.group.IUpdate;
import com.by.entity.User;
import com.by.service.UserService;
import io.swagger.annotations.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.DigestUtils;
import org.springframework.validation.BindingResult;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import springfox.documentation.annotations.ApiIgnore;

import java.util.Map;

@Api(tags = "用户管理")
@RestController
@RequestMapping("/v1")
public class UserController extends BaseController {
    @Autowired
    UserService userService;
    @Autowired
    TokenTemplate tokenTemplate;

    /*
     *
     * 账号唯一检查
     * */
    @ApiOperation("账号唯一检查")
    @GetMapping("/user/query")
    public ResultBean checkUser(@RequestParam(name = "account", required = true) String account) {
        int n = userService.queryBybName(account);
        if (n > 0) {
            return fail("账号已存在!");
        }
        return success("可以注册!");
    }

    @ApiOperation("用户登录")
    @PostMapping("/user/login")
    public ResultBean login(@Validated @RequestBody User user, BindingResult result) {
        validate(result);
        User u = userService.queryName(user.getAccount());
        if (null == u) {
            //说明不存在
            return fail("账号不存在");
        }
        //判断密码是否正确
        String pwd = DigestUtils.md5DigestAsHex(user.getPassword().getBytes());
        if (!pwd.equals(u.getPassword())) {
            System.out.println(pwd);
            System.out.println(u.getPassword());
            return fail("账号或密码不正确");
        }
        //判断账号状态
        if (u.getStatus() == 1) {
            return fail("该账号已经禁用!");
        }

        //将user转换为map
        Map map = BeanUtil.beanToMap(u);
        //移除密码
        map.remove("password");
        //生成Token
        String token = tokenTemplate.generateToken(map);
        map.put("token", token);


        return success("登陆成功", map);
    }
}
